package com.yunxi.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.yunxi.base.pojo.BaseApplyLevelVO;
import com.yunxi.base.service.BaseApplyLevelDubboService;
import com.yunxi.common.config.RedisCacheService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.util.DESUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.JwtUtils;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.dealer.service.PartnerDubboService;
import com.yunxi.sys.pojo.RoleUserVO;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.pojo.UserVO;
import com.yunxi.sys.service.RoleMenuDubboService;
import com.yunxi.sys.service.RoleUserDubboService;
import com.yunxi.sys.service.StaffDubboService;
import com.yunxi.sys.service.UserDubboService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2018/1/29.
 */
@RestController
@RequestMapping("/com")
@Api(tags = "sys:login", description = "登录接口")
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserDubboService userDubboService;

    //@Autowired
    //private RoleMenuService rmService;

    @Autowired
    PartnerDubboService partnerDubboService;

    @Autowired
    private RedisCacheService rcs;

    @Autowired
    StaffDubboService staffDubboService;

    @Autowired
    RoleMenuDubboService roleMenuDubboService;

    //@Autowired
    //BaseApplyLevelDubboService baseApplyLevelDubboService;

    @Autowired
    RoleUserDubboService roleUserDubboService;

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录",notes="根据用户名及密码登录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "login", value = "用户详细实体{\"userName\":\"admin\",\"password\":\"zgbtwl\"}", required = true, paramType = "body", dataType = "UserVO")
    })
    public ApiResult<LoginInfo> login(@RequestBody UserVO login) throws Exception {
        Map map = new HashMap();
        map.put("userCode", login.getUserName());
        LoginInfo info = new LoginInfo();
        login.setUserCode(login.getUserName());
        String passWord = login.getPassword();

        UserVO user = userDubboService.findUserByUserCode(map);
        if (user != null) {
            passWord = DESUtil.encrypt(passWord);
            if (!passWord.equals(user.getPassword())) {
                return ResponseUtil.fail(4002, "密码错误");
            }
            else if(user.getStatus().intValue() == 0){
                return ResponseUtil.fail(4003, "用户已停用");
            }
            else{
                String tokenId = JwtUtils.createJWT(user.getUserId()+"",user.getUserName(),1800000);
                map.put("token", tokenId);
                info.setToken(tokenId);
                info.setUser(user);
                info.setUserId(user.getUserId());
                info.setUserCode(user.getUserCode());
                info.setRealName(user.getRealName());
                info.setIsOpen(user.getIsOpen());
                info.setUserType(user.getUserType());
                if(user.getIsOpen().intValue()==1){
                    info.setMessage("观光模式");
                }
                //查询是否是渠道商
                PartnerVO partnerVO = partnerDubboService.getByUser(user);
                if(partnerVO!=null) {
                    info.setPartner(partnerVO);
                    info.setPartnerCode(partnerVO.getPartnerCode());
                }

                StaffVO staffVO = staffDubboService.getByUser(user);
                if (staffVO != null) {
                    if ("ups".equals(staffVO.getTenantId())) {
                        return ResponseUtil.fail(4004, "请使用销售渠道商账号登陆");
                    }
                    if ("sat".equals(login.getCurrSys()) && StringUtils.isEmpty(staffVO.getPartnerCode())) {
                        return ResponseUtil.fail(4005, "请使用渠道商账号登陆");
                    }
                    info.setStaff(staffVO);
                    info.setAccountNo(staffVO.getAccountNo());
                    info.setPartnerCode(staffVO.getPartnerCode());
                    info.setTenantId(staffVO.getTenantId());
                }

                Map map2 = new HashMap();
                List<RoleUserVO> roleList = roleUserDubboService.listByUserId(user.getUserId());

                //销售助手登录时，去除管理员角色、不允许管理员登录
                if ("sat".equals(login.getCurrSys())) {
                    List<RoleUserVO> satRoleList = new ArrayList<>();
                    roleList.forEach(roleUserVO -> {
                        if(!roleUserVO.getRoleCode().equals(DictConstant.USER_ROLE_PARTNER_ADMIN)){
                            satRoleList.add(roleUserVO);
                        }
                    });
                    if(CollectionUtils.isEmpty(satRoleList)){
                        return ResponseUtil.fail(4005, "请使用销售助手角色账号登陆");
                    }
                    map2.put("roleList",satRoleList);
                }else{
                    map2.put("roleList",roleList);
                }
                info.setSubMap(map2);
                /*
                //查询当前用户审核的审核级别
                BaseApplyLevelVO baseApplyLevelVO = new BaseApplyLevelVO();
                baseApplyLevelVO.setBusId(Constant.PMS_VERIFY_RETUR_VEHICLE);
                baseApplyLevelVO.setUserCode(user.getUserCode());
                List<BaseApplyLevelVO> baseApplyLevelVOList = baseApplyLevelDubboService.listByVo(baseApplyLevelVO);
                if(baseApplyLevelVOList != null && baseApplyLevelVOList.size() > 0){
                    info.setCurrentLevel(baseApplyLevelVOList.get(0).getCurrentLevel());
                }
                */

                rcs.set("token:"+tokenId, JSONObject.toJSONString(info), 50000);
                return ResponseUtil.ok(info);
            }
        }
        return ResponseUtil.fail(400, "用户不存在");
    }

    @PostMapping(value = "/getAuth")
    @ApiOperation(value = "得到个人信息和权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query"),
    })
    public Object getInfo(@RequestBody JSONObject requestJson, HttpServletRequest request) throws Exception {
        String token = requestJson.getString("token");
        String companyId = requestJson.getString("companyId");
        String departmentId = requestJson.getString("departmentId");
        Map<String, Object> map = new HashMap<String, Object>();
        //获得权限对应的菜单
        LoginInfo user = (LoginInfo)rcs.getObject("token:"+token,LoginInfo.class);


        String roleCode = request.getHeader("roleCode");

        if(user!=null){
            JSONObject vo = (JSONObject)user.getUser();
            map.put("userId", vo.get("userId"));
            map.put("userName", vo.get("userName"));
            map.put("companyId", companyId);
            map.put("departmentId", departmentId);
            map.put("token", token);
            map.put("type", "1");
            map.put("user",user);
            if(vo.getString("userCode").equals("admin")){
                map.put("access", new String[]{"super_admin"});
            }else{
                if(!"".equals(roleCode)){
                    String[] access = roleMenuDubboService.listMenuByRoleCode(roleCode);
                    map.put("access", access);
                }else{
                    String[] access = roleMenuDubboService.listMenuByUserId(vo.getString("userId"));
                    map.put("access", access);
                }

            }
            return ResponseUtil.ok(map);
        }else{
            return ResponseUtil.fail401();
        }
    }

    @PostMapping(value = "/getPartner")
    @ApiOperation(value = "得到个人信息和权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "departmentId", value = "部门id", required = true, paramType = "query")
    })
    public Object getPartner(@RequestBody JSONObject requestJson) throws Exception {
        String token = requestJson.getString("token");
        String companyId = requestJson.getString("companyId");
        String departmentId = requestJson.getString("departmentId");
        Map<String, Object> map = new HashMap<String, Object>();
        //获得权限对应的菜单
        LoginInfo user = (LoginInfo)rcs.getObject("token:"+token,LoginInfo.class);
        if(user!=null){
            JSONObject vo = (JSONObject)user.getUser();
            map.put("userId", vo.get("userId"));
            map.put("userName", vo.get("userName"));
            map.put("companyId", companyId);
            map.put("departmentId", departmentId);
            map.put("token", token);
            map.put("type", "1");
            map.put("user",user);
            if(vo.getString("userCode").equals("admin")){
                map.put("access", new String[]{"super_admin"});
            }else{
                //String[] access = rmService.selectMenuByUserIdCompanyIdType(user.getId(), companyId, ConstantTCB.MENU_TYPE_ADMIN);
                //map.put("access", access);
            }
            return ResponseUtil.ok(map);
        }else{
            return ResponseUtil.fail401();
        }
    }

    /**
     * 退出登录
     *
     * @throws Exception
     */
    @PostMapping(value = "/loginOut")
    @ApiOperation(value = "登出")
    public Object loginOut(HttpServletRequest request) throws Exception {
        //token缓存清空
        String token = request.getHeader("x-access-token");
        rcs.delete("token:"+token);
        return ResponseUtil.ok("退出登录成功");
    }
}
